package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.LoginFailedException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageBean;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.swing.*;
import java.beans.beancontext.BeanContext;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 登录失败重试次数上限
     */
    private static final int FAILED_RETRY_TIMES = 3;
    /**
     * redis记录用户登录失败次数key
     */
    private static final String USER_LOGIN_FAILED_COUNT = "USER:LOGIN:FAILED:COUNT:";
    /**
     * 设置登录时间
     */
    private static final Integer TIME_INTERVAL = 60;


    /**
     * 登录检查
     */
    @Override
    public EmployeeLoginVO checkLogin(EmployeeLoginDTO employeeLoginDTO) {

        //检查用户名
        Employee username = employeeMapper.checkUsernname(employeeLoginDTO.getUsername());
        ValueOperations Operations = redisTemplate.opsForValue();
        //获得对象的名字,然后创建响应的计时器对象
        RedisAtomicInteger counter = getRedisCounter(USER_LOGIN_FAILED_COUNT + username.getUsername());

        //判断是否被锁定
        if (redisTemplate.hasKey(MessageConstant.ACCOUNT_LOCK)) {
            Long expire = redisTemplate.getExpire(MessageConstant.ACCOUNT_LOCK);
            throw new AccountLockedException(MessageConstant.ACCOUNT_DOWN + expire);
        }

        //大于预定次数就锁定
        if (counter.get() > FAILED_RETRY_TIMES) {
            Operations.set(MessageConstant.ACCOUNT_LOCK, 1, TIME_INTERVAL, TimeUnit.MINUTES);

            redisTemplate.delete(USER_LOGIN_FAILED_COUNT + username.getUsername());

        }


        //判断账号
        if (username == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //判断密码
//        //对前端的密码进行加密
//        String s = DigestUtils.md5DigestAsHex(employeeLoginDTO.getPassword().getBytes(StandardCharsets.UTF_8));
        //用BCrypt进行加密
        String hashedPassword = BCrypt.hashpw(employeeLoginDTO.getPassword(), BCrypt.gensalt());

        log.info("用BCrypt进行加密{}", hashedPassword);

        if (!BCrypt.checkpw(employeeLoginDTO.getPassword(),username.getPassword())) {
            counter.getAndIncrement();
            throw new LoginFailedException(MessageConstant.PASSWORD_ERROR);
        }
        //判断员工账号状态
        if (username.getStatus() != StatusConstant.ENABLE) {
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //定义用于存放放入jwt中的信息
        Map<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.EMP_ID, username.getId());
        map.put(JwtClaimsConstant.USER_ID, username.getIdNumber());
        map.put(JwtClaimsConstant.PHONE, username.getPhone());
        map.put(JwtClaimsConstant.USERNAME, username.getUsername());
        map.put(JwtClaimsConstant.NAME, username.getName());

        //创建JWT
        String jwt = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), map);

        //返回数据
        EmployeeLoginVO build = EmployeeLoginVO.builder().id(username.getId()).userName(username.getUsername()).name(username.getName())
                .token(jwt).build();

        redisTemplate.delete(USER_LOGIN_FAILED_COUNT + username.getUsername());

        return build;

    }

    /**
     * 新增员工功能
     *
     * @param employeeDTO
     */
    @Override
    public void addEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();

        BeanUtils.copyProperties(employeeDTO, employee);//克隆对象
        employee.setStatus(StatusConstant.ENABLE);//通过长亮设置状态

        //设置默认密码，一定要加密！通过BCrypt加密
        employee.setPassword(BCrypt.hashpw(MessageConstant.ORIGINAL_PASSWORD, BCrypt.gensalt()));

        //设置创建时间和更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //设置创建人和修改人id 4
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(10L);


        employeeMapper.insert(employee);


    }

    /**
     * 分页查询功能
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageBean pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {

        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Object> page = employeeMapper.pageQuery(employeePageQueryDTO);
        //另一种建立方法
        return PageBean.builder().total(page.getTotal())
                .records(page.getResult())
                .build();
//        return new PageBean(page.getTotal(), page.getResult());

    }

    /**
     * 更改员工的状态
     *
     * @param status
     * @param id
     */
    @Override
    public void setStatus(Integer status, Long id) {
//        Employee employee = new Employee();
//        employee.setStatus(status);
//        employee.setId(id);
        Employee employee =
                Employee
                        .builder()
                        .id(id)
                        .status(status)
                        .updateTime(LocalDateTime.now())
                        .build();
        employeeMapper.updateEmp(employee);
    }

    /**
     * 根据id查找员工
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 更新员工
     *
     * @param employeeDTO
     */
    @Override
    public void updateById(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setPassword(BCrypt.hashpw(MessageConstant.ORIGINAL_PASSWORD, BCrypt.gensalt()));
        //设置更新人和更新时间
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser(BaseContext.getCurrentId());

        employeeMapper.updateEmp(employee);
    }

    /**
     * 修改员工密码
     *
     * @param passwordEditDTO shuju
     */
    @Override
    public void changePassword(PasswordEditDTO passwordEditDTO) {
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
        //旧密码校验
        Employee employee = employeeMapper.getById(passwordEditDTO.getEmpId());

        boolean checkpw = BCrypt.checkpw(passwordEditDTO.getOldPassword(), employee.getPassword());
        if (checkpw) {
            //新密码加密
            String newpw = BCrypt.hashpw(passwordEditDTO.getNewPassword(), BCrypt.gensalt());
            employee.setPassword(newpw);
            //更改密码
            employeeMapper.updateEmp(employee);
        } else
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
    }


    RedisAtomicInteger getRedisCounter(String key) { //用于在 Redis 中实现原子操作的计数器
        RedisAtomicInteger counter =
                new RedisAtomicInteger(key, redisTemplate.getConnectionFactory());  //给相应的key获得一个计数器
        if (counter.get() == 0) {
            // 设置过期时间，1分组
            counter.expire(TIME_INTERVAL, TimeUnit.SECONDS);
        }
        return counter;
    }
}
